//
//  RegisterViewController.m
//  翼安保
//
//  Created by duzhi on 2024/4/17.
//

#import "RegisterViewController.h"
#import "regular.h"
#import "LoginApi.h"
#import "AddressModel.h"
#import "AddressView.h"

@interface RegisterViewController ()
@property (nonatomic, strong) NSString      *phone;
@property (nonatomic, strong) NSString      *name;
@property (nonatomic, strong) NSString      *corporation;
@property (nonatomic, strong) NSString      *managePhone;
@property (nonatomic, strong) NSString      *pCode;
@property (nonatomic, strong) NSString      *cCode;
@property (nonatomic, strong) NSString      *dCode;
@property (nonatomic, strong) UIButton      *cityButton;
@property (nonatomic, strong) AddressView   *addressView;
@property (nonatomic, strong) NSArray       *cityInfos;
@property (nonatomic, strong) NSMutableArray *tasks;
@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatUI];
    [self getCityInfos:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)back {
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)creatUI {
    NewsBigButton *backButton = [NewsBigButton new];
    [backButton setBackgroundImage:[UIImage imageNamed:@"back_black_26x26"] forState:0];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(relativeWidth(15));
        make.centerY.mas_equalTo(self.view.mas_top).mas_offset(kiPhoneX_Top_Height+relativeWidth(22));
    }];
    
    UILabel *titleL = [UILabel new];
    titleL.text = @"注册";
    titleL.font = [UIFont boldSystemFontOfSize:relativeWidth(20)];
    titleL.textColor = [UIColor blackColor];
    [self.view addSubview:titleL];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(backButton.mas_bottom).offset(relativeWidth(20));
    }];
    
    UILabel *tipL = [UILabel new];
    tipL.text = @"手机号仅用于登录和保护账号安全";
    tipL.font = [UIFont systemFontOfSize:relativeWidth(13)];
    tipL.textColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [self.view addSubview:tipL];
    [tipL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(titleL.mas_bottom).offset(relativeWidth(10));
    }];
    
    UIView *theLastInputView = nil;
    for (int i=0; i<4; i++) {
        UIView *inputView = [self creatInputView:i];
        [inputView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.top.mas_equalTo(tipL.mas_bottom).offset(relativeWidth(20)+i*relativeWidth(60));
            make.height.mas_equalTo(relativeWidth(60));
        }];
        if(i == 3) {
            theLastInputView = inputView;
        }
    }
    
    UIButton *cityButton = [UIButton new];
    [cityButton setTitle:@"所属地区" forState:0];
    cityButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    cityButton.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    cityButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    cityButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [cityButton setTitleColor:[[UIColor blackColor] colorWithAlphaComponent:0.3] forState:UIControlStateNormal];
    [cityButton setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    [cityButton addTarget:self action:@selector(cityButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cityButton];
    [cityButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(relativeWidth(50));
        make.right.mas_equalTo(relativeWidth(-50));
        make.top.mas_equalTo(theLastInputView.mas_bottom).offset(0);
        make.height.mas_equalTo(relativeWidth(60));
    }];
    self.cityButton = cityButton;
    
    UIButton *registerButton = [UIButton new];
    registerButton.backgroundColor = [UIColor grayColor];
    [registerButton setTitle:@"注册" forState:0];
    registerButton.layer.cornerRadius = relativeWidth(22);
    [registerButton setTitleColor:[UIColor whiteColor]  forState:0];
    [registerButton addTarget:self action:@selector(registerClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registerButton];
    [registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(relativeWidth(relativeWidth(-40)));
        make.height.mas_equalTo(relativeWidth(44));
        make.left.mas_equalTo(relativeWidth(40));
        make.top.mas_equalTo(cityButton.mas_bottom).offset(relativeWidth(60));
    }];
    
    self.addressView = [AddressView new];
    self.addressView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, relativeWidth(200));
    Weak(wself, self)
    self.addressView.confirmBlock = ^(AddressModel * _Nonnull p, ChooseAreaListCityModel * _Nonnull c, ChooseAreaListDistrictModel * _Nonnull d) {
        [wself.cityButton setTitle:[NSString stringWithFormat:@"%@%@%@",p.Description,c.Description,d.Description] forState:0];
        wself.cityButton.selected = YES;
        wself.pCode = p.ID;
        wself.cCode = c.ID;
        wself.dCode = d.ID;
    };
    [self.view addSubview:self.addressView];
}

- (UIView *)creatInputView:(int)type {
    UIView *inputView = [UIView new];
    inputView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:inputView];

    UITextField *phoneTextField = [UITextField new];
    phoneTextField.font         = [UIFont systemFontOfSize:relativeWidth(14)];
    phoneTextField.tintColor    = [UIColor blackColor];
    [inputView addSubview:phoneTextField];
    [phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(relativeWidth(50));
        make.right.mas_equalTo(relativeWidth(-50));
        make.bottom.mas_equalTo(relativeWidth(-20));
    }];
    
    UIView *lineView = [UIView new];
    lineView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
    [self.view addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(relativeWidth(50));
        make.right.mas_equalTo(relativeWidth(-50));
        make.top.mas_equalTo(inputView.mas_bottom).mas_offset(-0.5);
        make.height.mas_equalTo(0.5);
    }];
    NSString *placeHolder = @"";
    switch (type) {
        case 0:
            placeHolder = @"请输入姓名";
            phoneTextField.keyboardType = UIKeyboardTypeDefault;
            [phoneTextField addTarget:self action:@selector(nameTextChange:) forControlEvents:UIControlEventEditingChanged];
            break;
        case 1:
            placeHolder = @"请输入手机号";
            phoneTextField.keyboardType = UIKeyboardTypeNamePhonePad;
            [phoneTextField addTarget:self action:@selector(phoneTextChange:) forControlEvents:UIControlEventEditingChanged];
            break;
        case 2:
            placeHolder = @"请输入公司名称";
            phoneTextField.keyboardType = UIKeyboardTypeDefault;
            [phoneTextField addTarget:self action:@selector(corporationTextChange:) forControlEvents:UIControlEventEditingChanged];
            break;
        case 3:
            placeHolder = @"请输入管理员手机号";
            phoneTextField.keyboardType = UIKeyboardTypeNamePhonePad;
            [phoneTextField addTarget:self action:@selector(manageTextChange:) forControlEvents:UIControlEventEditingChanged];
//            lineView.hidden = YES;
            break;
            
        default:
            break;
    }
    phoneTextField.placeholder  = placeHolder;
    return inputView;
}


- (void)phoneTextChange:(UITextField *)textFiled {
    self.phone = textFiled.text;
}
- (void)nameTextChange:(UITextField *)textFiled {
    self.name = textFiled.text;
}
- (void)corporationTextChange:(UITextField *)textFiled {
    self.corporation = textFiled.text;
}
- (void)manageTextChange:(UITextField *)textFiled {
    self.managePhone = textFiled.text;
}

- (void)registerClick {
    if (![regular checkPhoneNumFormat:self.phone]) {
        [MBProgressHUD showTextHUD:@"手机号码不合法" superView:self.view];
        return;
    }
    if (![regular checkPhoneNumFormat:self.managePhone]) {
        [MBProgressHUD showTextHUD:@"管理员手机号码不合法" superView:self.view];
        return;
    }
    if (allTrim(self.name).length == 0) {
        [MBProgressHUD showTextHUD:@"请输入姓名" superView:self.view];
        return;
    }
    if (allTrim(self.corporation).length == 0) {
        [MBProgressHUD showTextHUD:@"请输入公司名称" superView:self.view];
        return;
    }
    if (allTrim(self.pCode).length == 0||allTrim(self.cCode).length == 0||allTrim(self.dCode).length == 0) {
        [MBProgressHUD showTextHUD:@"请选择地区" superView:self.view];
        return;
    }
    [self registerApi];
}

- (void)cityButtonClick {
    [self.view endEditing:YES];
    if (!self.cityInfos) {
        [self getCityInfos:^{
            [self showAddress];
        }];
    }else {
        [self showAddress];
    }
}

- (void)showAddress {
    self.addressView.datas = self.cityInfos;
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self.addressView.frame = CGRectMake(0, ScreenHeight-relativeWidth(200), ScreenWidth, relativeWidth(200));
    } completion:nil];
}

#pragma mark api
- (void)registerApi {
    NSMutableDictionary *dic = [NSMutableDictionary new];
    dic[@"fPhone"] = self.phone;
    dic[@"fName"] = self.name;
    dic[@"fCompanyName"] = self.corporation;
    dic[@"fManagerPhone"] = self.managePhone;
    dic[@"fProvinceCode"] = self.pCode;
    dic[@"fCityCode"] = self.cCode;
    dic[@"fAreaCode"] = self.dCode;
    [[AFNNetWorkManager shareAFNNetWorkManager] postJson:registerUrl parameters:dic success:^(NSURLSessionDataTask *task, Result *result) {
        if (result.code == 200) {
            [MBProgressHUD showTextHUD:@"注册成功,等待管理员审核通过"];
            [self.navigationController popViewControllerAnimated:NO];
        }else {
            [MBProgressHUD showTextHUD:result.msg];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD showTextHUD:@"请检查网络设置"];
    }];
}

- (void)getCityInfos:(void (^)(void))complete {
    //取消上一次请求
    NSMutableArray *canceTasks = [NSMutableArray new];
    [self.tasks enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSURLSessionDataTask *task = obj;
        if (task.state != NSURLSessionTaskStateCompleted) {
            [task cancel];
            [canceTasks addObject:task];
        }
    }];
    [self.tasks removeObjectsInArray:canceTasks];
    NSURLSessionDataTask *task = [[AFNNetWorkManager shareAFNNetWorkManager] Get:cityInfoUrl parameters:nil success:^(NSURLSessionDataTask *task, Result *result) {
        if (result.code == 200) {
            self.cityInfos = [AddressModel mj_objectArrayWithKeyValuesArray:result.data];
            if ((complete)) {
                complete();
            }
        }else {
            [MBProgressHUD showTextHUD:result.msg];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
    }];
    if (task.state != NSURLSessionTaskStateCompleted && self.tasks) {
        [self.tasks addObject:task];
    }
}

@end
